﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SCM.Model.DBEntity;
using SCM.Servie.IBusiness;

namespace SCM.Manage.Controllers
{
    [Authorize]
    public class BasicIngredientController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult SelectView()
        {
            return View();
        }

        #region 添加
        public ActionResult AddView()
        {
            return View();
        }

        public IActionResult Add(T_Material_Ingredient entity)
        {
            #region 数据验证
            if (string.IsNullOrWhiteSpace(entity.CASNo))
            {
                return Error("分类标识不能为空");
            }

            if (string.IsNullOrWhiteSpace(entity.CName))
            {
                return Error("中文名不能为空");
            }

            if (string.IsNullOrWhiteSpace(entity.EName))
            {
                return Error("英文名不能为空");
            }
            #endregion
            entity.Creator = CurrentUserId;
            entity.CreatorName = CurrentUserName;

            var service = GetService<IMaterialIngredientService>();
            bool result = service.Add(entity) != null ? true : false;
            return result ? GetOk(result) : Error("保存失败");
        }
        #endregion

        #region 查询
        [HttpPost]
        public IActionResult Search(string casNo, string cName, string eName, int index = 1)
        {
            var service = GetService<IMaterialIngredientService>();
            var dataPage = service.Query(casNo, cName, eName, new Common.PageInfo() { PageIndex = index, PageSize = 10 });
            return GetOk(new { totalCount = dataPage.Page.DataCount, items = dataPage.Data });
        }

        #endregion

        #region 编辑
        public IActionResult EditView(string id)
        {
            var model = GetService<IMaterialIngredientService>().GetById(id);
            return View(model);
        }

        public IActionResult Modify(T_Material_Ingredient entity)
        {
            entity.ModifyUserId = CurrentUserId;
            entity.ModifyUserName = CurrentUserName;

            bool result = GetService<IMaterialIngredientService>().Update(entity);
            return result ? GetOk(result) : Error("保存失败");
        }
        #endregion

        #region 删除
        /// <summary>
        /// 删除  【支持批量操作】
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IActionResult Delete(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids) || ids.Split(',').Length < 0)
            {
                return Error("请选择数据");
            }
            var delIds = ids.Split(',').ToList();
            bool result = GetService<IMaterialIngredientService>().Delete(delIds);
            return result ? GetOk(result) : Error("删除失败");
        }
        #endregion

        #region 导入
        public IActionResult ImportView()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Import()
        {
            try
            {
                if (Request.Form.Files == null || Request.Form.Files.Count <= 0)
                {
                    return Error("请选择您要导入的文件!");
                }

                var excelFile = Request.Form.Files[0];
                string fileType = excelFile.ContentType;
                string fileName = excelFile.FileName.ToLower();
                string fileExt = Path.GetExtension(fileName);
                string fileAllowExt = "*.xlsx;*.xls";

                if (fileAllowExt.IndexOf(fileExt) < 0)
                {
                    return Error("请选择正确格式的Excel文件!");
                }

                #region 解析文件

                DataTable FileSource = NPOIHelper.ImportExceltoDt(excelFile.OpenReadStream());
                #endregion

                //保存解析数据集合
                List<T_Material_Ingredient> items = new List<T_Material_Ingredient>();
                foreach (var item in FileSource.AsEnumerable())
                {
                    T_Material_Ingredient model = new T_Material_Ingredient();
                    model.CASNo = item.Field<string>("CAS");
                    model.ECNo = item.Field<string>("EC No") ?? "";
                    model.EName = item.Field<string>("英文名称") ?? "";
                    model.CName = item.Field<string>("中文名称") ?? "";
                    model.MF = item.Field<string>("MF");
                    items.Add(model);
                }

                if (items != null && items.Count > 0)
                {
                    bool result = GetService<IMaterialIngredientService>().SaveOrUpdate(items);
                    return result ? GetOk(result) : Error("导入失败");
                }
                return GetOk("导入成功");
            }
            catch (Exception ex)
            {
                return Error("导入失败，信息：" + ex.Message);
            }
        }

        #endregion
    }
}
